package com.qf.android.huihui.view.activity;

import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v7.app.AppCompatActivity;
import android.view.View;

import com.alibaba.fastjson.JSON;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.qf.android.huihui.R;
import com.qf.android.huihui.bean.ADentity;
import com.qf.android.huihui.databinding.ActivityWelcomeBinding;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

public class WelcomeActivity extends AppCompatActivity {
    public static final String AD_URL = "http://adse.ximalaya.com/ting/loading?appid=0&device=android&name=loading&network=wifi&operator=0&version=4.3.98";
    private ActivityWelcomeBinding binding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.activity_welcome);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_welcome);
        intiData();
        TimeCount();
        binding.tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(WelcomeActivity.this, MainActivity.class));
                finish();
            }
        });

    }

    private void intiData() {
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        StringRequest stringRequest = new StringRequest(StringRequest.Method.GET, AD_URL, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    JSONObject object = new JSONObject(response);
                    JSONArray jsonArray = object.getJSONArray("data");
                    List<ADentity> aDentities = JSON.parseArray(jsonArray.toString(), ADentity.class);
                    binding.setAd(aDentities.get(0));
                    binding.setVariable(com.qf.android.huihui.BR.ad, aDentities.get(0));

                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        }, null);
        requestQueue.add(stringRequest);


    }
    //广告倒计时的方法
    public void TimeCount() {
        new CountDownTimer(4 * 1000, 1000) {
            @Override
            public void onTick(long l) {
                binding.tv.setText("跳过广告 " + l / 1000 + " s");
            }

            @Override
            public void onFinish() {
                startActivity(new Intent(WelcomeActivity.this, MainActivity.class));
                finish();
            }
        }.start();
    }
}
